﻿using Furion.RemoteRequest.Extensions;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Text;

namespace apitest.Application.Test.Services
{
    [DynamicApiController]
    public class DSMService
    {
        private static readonly HttpClient client = new HttpClient();
        static string _sid = "I5WJy_4rqPvk-HHlVllUKfOD9I4I2mZvPgPiddJFpts3QAnT0EKzNYfWlYRT1yIldxMvaV8V8s4G88bIa1BavM";
        public async Task<dynamic> Login()
        {

            var url = "http://192.168.169.233:5000/webapi/auth.cgi?api=SYNO.API.Auth&version=3&method=login&account=it&passwd=Ast.123456&session=FileStation&format=cookie";
            //var res = await url.GetAsStringAsync();
            var res = await client.GetStringAsync(url);
            return res;
        }
        public async Task<dynamic> ShareFile()
        {
            var url = $"http://192.168.169.233:5000/webapi/entry.cgi?api=SYNO.FileStation.Sharing&version=3&method=create&path=/IT/111/123.txt&password=12344&date_expired=\"2025-02-25\"&_sid={_sid}";
            var res = await url.GetAsStringAsync();
            return JObject.Parse(res);
        }

        public async Task<dynamic> Upload()
        {
            using (var multipartFormDataContent = new MultipartFormDataContent())
            {
                var values = new[]
                {
            new KeyValuePair<string, string>("path", "/test111"),
             new KeyValuePair<string, string>("create_parents", "true"),
            new KeyValuePair<string, string>("overwrite", "true"),
        };

                foreach (var keyValuePair in values)
                {
                    multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
                        String.Format("\"{0}\"", keyValuePair.Key));
                }
                var filePath = "./321.txt";
                var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                multipartFormDataContent.Add(new StreamContent(fileStream),
                    "file",
                    "321.txt");
                var _sid = "tpqYjy2nz9awuldrP9jgiQX7j-hsFBR8kHrGHBuPumIcRfQUx-TVQlLUfAcApZQKhjfeQhHNvf5xHWi8e5c0Uo";
                var url = $"http://192.168.169.233:5000/webapi/entry.cgi?api=SYNO.FileStation.Upload&version=2&method=upload&_sid={_sid}";
                url.SetBody(new
                {
                    multipartFormDataContent
                });
                return await url.PostAsStringAsync();
                //var res = await client.PostAsync(url, multipartFormDataContent);
                //return res.Content.ReadAsStringAsync().Result;
            }
        }

        public async Task<dynamic> UploadFile(IFormFile file)
        {
            var _sid = "tpqYjy2nz9awuldrP9jgiQX7j-hsFBR8kHrGHBuPumIcRfQUx-TVQlLUfAcApZQKhjfeQhHNvf5xHWi8e5c0Uo";
            var url = $"http://192.168.169.233:5000/webapi/entry.cgi?api=SYNO.FileStation.Upload&version=2&method=upload&_sid={_sid}";
            var filePath = "./321.txt";
            var formData = new MultipartFormDataContent();
            var dic = new Dictionary<string, string>();
            dic.Add("path", "/test111");
            dic.Add("create_parents", "true");
            dic.Add("overwrite", "true");
            foreach (var item in dic.Keys)
            {
                var sc = new StringContent(dic[item]);
                //sc.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
                formData.Add(sc, item);
            }

            var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            var bytes = File.ReadAllBytes(filePath);
            ByteArrayContent fileContent = new ByteArrayContent(bytes);
            //fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
            //fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            StreamContent streamContent = new StreamContent(fs);
            //streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
            //streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            formData.Add(streamContent, "file", "222.txt");
            formData.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data; boundary=--------------------------058320479839921511762476");
            return await client.PostAsync(url, formData).Result.Content.ReadAsStringAsync();
        }

        [RequestSizeLimit(100000000)]
        public void Up(IFormFile file)
        {
            try
            {
                var path = "/app/集团会议管理";
                FileStream fs = new FileStream(System.IO.Path.Combine(path, file.FileName), FileMode.OpenOrCreate, FileAccess.ReadWrite);
                file.CopyTo(fs);
                fs.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public void down(string fileName)
        {
            try
            {
                var path = "/app/集团会议管理";
                File.Copy(System.IO.Path.Combine(path, fileName), $"./uploads/{fileName}");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public async Task<dynamic> bbb()
        {

            var _sid = "tpqYjy2nz9awuldrP9jgiQX7j-hsFBR8kHrGHBuPumIcRfQUx-TVQlLUfAcApZQKhjfeQhHNvf5xHWi8e5c0Uo";
            var url = $"http://192.168.169.233:5000/webapi/entry.cgi?api=SYNO.FileStation.Upload&version=2&method=upload&_sid={_sid}";
            var filePath = "./321.txt";
            var dic = new Dictionary<string, string>
            {
                { "path", "/test111" },
                {"create_parents","true" },
                {"overwrite","true" },
            };
            var formData = new MultipartFormDataContent();
            foreach (var key in dic.Keys)
            {
                var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(dic[key]));
                dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name = key
                };
                formData.Add(dataContent);
            }

            var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            var bytes = File.ReadAllBytes(filePath);
            ByteArrayContent fileContent = new ByteArrayContent(bytes);
            StreamContent streamContent = new StreamContent(fs);

            Stream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);//转成stream流
            var sc = new StreamContent(fileStream);
            var Content = new ByteArrayContent(bytes);//创建文件的content


            formData.Add(Content, "file");


            //formData.Add(streamContent, "file", "aaa.txt");
            return await client.PostAsync(url, formData).Result.Content.ReadAsStringAsync();

        }

        public string ccc(IFormFile file)
        {
            var _sid = "tpqYjy2nz9awuldrP9jgiQX7j-hsFBR8kHrGHBuPumIcRfQUx-TVQlLUfAcApZQKhjfeQhHNvf5xHWi8e5c0Uo";
            var url = $"http://192.168.169.233:5000/webapi/entry.cgi?api=SYNO.FileStation.Upload&version=2&method=upload&_sid={_sid}";
            //分割字符串
            var boundary = "----" + DateTime.Now.Ticks.ToString("x");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((a, b, c, d) => true);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            MemoryStream stream = new MemoryStream();
            byte[] b;
            //file.CopyTo(stream);

            #region 将表单写入内存流
            var str = "";
            var dic = new Dictionary<string, string>
            {
                { "path", "/test111" },
                {"create_parents","true" },
                {"overwrite","true" },
            };
            foreach (var key in dic.Keys)
            {
                str = $"\r\n--{boundary}\r\nContent-Disposition: multipart/form-data; name=\"{key}\";\r\n\r\n{dic[key]}\r\n\r\n";
                b = Encoding.UTF8.GetBytes(str);
                stream.Write(b, 0, b.Length);
                Console.WriteLine(str);
            }
            #endregion

            #region 将文件写入到内存流
            byte[] filedata = File.ReadAllBytes("./321.txt"); ;
            str = string.Format("\r\n--{0}\r\nContent-Disposition: multipart/form-data; name=\"{1}\"; filename=\"{2}\"\r\n\r\n",
              boundary, "file", "3233.txt");
            b = Encoding.UTF8.GetBytes(str);
            stream.Write(b, 0, b.Length);
            stream.Write(filedata, 0, filedata.Length);

            #endregion
            //结束标记
            byte[] foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
            stream.Write(foot_data, 0, foot_data.Length);
            Stream reqStream = request.GetRequestStream();
            stream.Position = 0L;
            //将Form表单生成流写入到请求流中
            stream.CopyTo(reqStream);
            stream.Close();
            reqStream.Close();
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();//获取响应
                }
            }
        }

        public dynamic ddd()
        {
            using (HttpClient client = new HttpClient())
            {

                string boundary = string.Format("----WebKitFormBoundary{0}", DateTime.Now.Ticks.ToString("x"));
                var _sid = "tpqYjy2nz9awuldrP9jgiQX7j-hsFBR8kHrGHBuPumIcRfQUx-TVQlLUfAcApZQKhjfeQhHNvf5xHWi8e5c0Uo";
                var url = $"http://192.168.169.233:5000/webapi/entry.cgi?api=SYNO.FileStation.Upload&version=2&method=upload&_sid={_sid}";
                MultipartFormDataContent content = new MultipartFormDataContent(boundary);

                #region 设置请求参数

                content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                var dic = new Dictionary<string, string>
            {
                { "path", "/test111" },
                {"create_parents","true" },
                {"overwrite","true" },
            };
                foreach (var key in dic.Keys)
                {
                    content.Add(new StringContent(dic[key]), key);
                }
                
                #endregion
                var fullPath = "./321.txt";
                string fileName = "321.txt";

                #region Stream请求

                FileStream fStream = File.Open(fullPath, FileMode.Open, FileAccess.Read);

                content.Add(new StreamContent(fStream, (int)fStream.Length), "file", fileName);

                #endregion


                var result = client.PostAsync(url, content).Result;

                try
                {
                    if (result.IsSuccessStatusCode)
                    {
                        string rslt = result.Content.ReadAsStringAsync().Result;

                        Debug.WriteLine(rslt);

                        return rslt;
                    }
                    return null;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(string.Format("获取服务器返回结果错误：消息：{0},堆栈：{1}", ex.Message, ex.StackTrace));
                    return "";
                }
                finally
                {
                    //关闭文件流
                    fStream.Close();
                    client.Dispose();
                }
            }
        }
    }
}
